package com.jjyd.crlp.services.impl;

import com.jjyd.crlp.domain.entity.UserAuth;
import com.jjyd.crlp.domain.entity.Users;
import com.jjyd.crlp.domain.entity.type.LoginType;
import com.jjyd.crlp.domain.repository.UserAuthRepo;
import com.jjyd.crlp.domain.repository.UsersRepo;
import com.jjyd.crlp.model.dto.register.RegisterLoginDto;
import com.jjyd.crlp.services.RegisterService;
import com.jjyd.crlp.util.check.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UsersRepo usersRepo;
    @Autowired
    private UserAuthRepo userAuthRepo;

    /**
     * 注册用户用于登陆的信息
     *  用户名如果已经存在，则提示，若不存在，则新建一个用户
     *
     * @param registerLoginDto
     * @return
     */
    @Override
    public Integer register(RegisterLoginDto registerLoginDto) {
        String username = registerLoginDto.getUsername();
        LoginType loginType = registerLoginDto.getLoginType();
        String password = registerLoginDto.getPassword();

        UserAuth userAuth = userAuthRepo.getByRemoveFalseAndIdentifier(username);
        CheckUtil.check("用户已经注册", userAuth == null);

        Users users = new Users();
        users.setNickName(registerLoginDto.getNickName());
        Integer userId = usersRepo.save(users).getId();

        userAuth = new UserAuth();
        userAuth.setUserId(userId);
        userAuth.setIdentifier(username);
        userAuth.setCredential(password);
        userAuth.setLoginType(loginType);
        return userAuthRepo.save(userAuth).getId();
    }

}
